<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>AA旅游记账本 Pro</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            -webkit-tap-highlight-color: transparent;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: linear-gradient(135deg, #f5f7fa 0%, #e4edf5 100%);
            color: #333;
            line-height: 1.6;
            min-height: 100vh;
            padding-bottom: 70px;
            touch-action: manipulation;
        }

        .container {
            max-width: 600px;
            margin: 0 auto;
            padding: 15px;
            position: relative;
        }

        /* 头部样式 */
        .header {
            background: linear-gradient(135deg, #43cea2 0%, #185a9d 100%);
            color: white;
            padding: 25px 20px;
            text-align: center;
            border-radius: 20px;
            margin-bottom: 25px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            position: relative;
            overflow: hidden;
        }

        .header-content {
            position: relative;
            z-index: 1;
        }

        .trip-selector {
            background: rgba(255,255,255,0.2);
            border: none;
            color: white;
            padding: 10px 15px;
            border-radius: 10px;
            font-size: 16px;
            width: 100%;
            margin-top: 10px;
            backdrop-filter: blur(5px);
        }

        .trip-selector option {
            background: #185a9d;
            color: white;
        }

        /* 卡片样式 */
        .card {
            background: rgba(255, 255, 255, 0.85);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            padding: 25px;
            margin-bottom: 25px;
            box-shadow: 0 8px 20px rgba(0, 0, 0, 0.05);
            border: 1px solid rgba(255, 255, 255, 0.5);
            transition: transform 0.3s ease, box-shadow 0.3s ease;
            opacity: 0;
            animation: fadeInUp 0.5s forwards;
            transform: translateZ(0);
            backface-visibility: hidden;
            perspective: 1000;
        }

        @keyframes fadeInUp {
            to {
                opacity: 1;
                transform: translateY(0);
            }
            from {
                opacity: 0;
                transform: translate3d(0, 20px, 0);
            }
        }

        /* 统计卡片 */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
            gap: 15px;
            margin-bottom: 25px;
        }

        .stat-card {
            background: rgba(255, 255, 255, 0.7);
            border-radius: 15px;
            padding: 20px;
            text-align: center;
            transition: all 0.3s;
            border: 1px solid rgba(225, 232, 237, 0.5);
        }

        .stat-value {
            font-size: 24px;
            font-weight: bold;
            color: #185a9d;
            margin-bottom: 5px;
        }

        .stat-label {
            font-size: 13px;
            color: #5a7a9a;
        }

        /* 表单元素 */
        .form-group {
            margin-bottom: 20px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #185a9d;
            font-size: 15px;
        }

        input, select, textarea {
            width: 100%;
            padding: 14px;
            border: 2px solid #e1e8ed;
            border-radius: 12px;
            font-size: 16px;
            transition: all 0.3s;
            background: rgba(255, 255, 255, 0.7);
            -webkit-appearance: none;
            appearance: none;
        }

        input:focus, select:focus, textarea:focus {
            outline: none;
            border-color: #43cea2;
            box-shadow: 0 0 0 3px rgba(67, 206, 162, 0.2);
        }

        /* 按钮样式 */
        .btn {
            background: linear-gradient(135deg, #43cea2 0%, #185a9d 100%);
            color: white;
            border: none;
            padding: 14px 20px;
            border-radius: 12px;
            font-size: 16px;
            cursor: pointer;
            transition: all 0.3s;
            width: 100%;
            font-weight: 600;
            letter-spacing: 0.5px;
            position: relative;
            overflow: hidden;
            touch-action: manipulation;
        }

        .btn:active {
            transform: scale(0.98);
        }

        .btn-secondary {
            background: linear-gradient(135deg, #a1c4fd 0%, #c2e9fb 100%);
            color: #185a9d;
        }

        .btn-danger {
            background: linear-gradient(135deg, #ff9a9e 0%, #fad0c4 100%);
            color: #d32f2f;
        }

        .btn-small {
            padding: 8px 15px;
            font-size: 14px;
            width: auto;
            border-radius: 8px;
        }

        /* 成员标签 */
        .member-list {
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
            margin-top: 15px;
        }

        .member-tag {
            background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
            padding: 8px 16px;
            border-radius: 20px;
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s;
            border: 1px solid rgba(255, 255, 255, 0.5);
            animation: fadeIn 0.3s;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: scale(0.9); }
            to { opacity: 1; transform: scale(1); }
        }

        .member-tag .remove {
            cursor: pointer;
            color: #ff9a9e;
            font-weight: bold;
            transition: all 0.3s;
            width: 20px;
            height: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
        }

        .member-tag .remove:hover {
            color: #d32f2f;
            background: rgba(255,255,255,0.5);
        }

        /* 支出列表 */
        .expense-list {
            max-height: 400px;
            overflow-y: auto;
            -webkit-overflow-scrolling: touch;
            transform: translateZ(0);
        }

        .expense-item {
            background: rgba(255, 255, 255, 0.7);
            border-radius: 15px;
            padding: 18px;
            margin-bottom: 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            transition: all 0.3s;
            border: 1px solid rgba(225, 232, 237, 0.5);
            position: relative;
            overflow: hidden;
            animation: slideInLeft 0.4s;
            will-change: transform;
        }

        @keyframes slideInLeft {
            from { transform: translateX(-20px); opacity: 0; }
            to { transform: translateX(0); opacity: 1; }
        }

        .expense-item::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 5px;
            height: 100%;
            background: linear-gradient(to bottom, #43cea2, #185a9d);
        }

        .expense-amount {
            font-size: 20px;
            font-weight: bold;
            color: #185a9d;
            margin-bottom: 5px;
        }

        .expense-actions {
            display: flex;
            gap: 10px;
        }

        .icon-btn {
            background: none;
            border: none;
            cursor: pointer;
            padding: 8px;
            border-radius: 50%;
            transition: all 0.3s;
            width: 36px;
            height: 36px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: rgba(225, 232, 237, 0.3);
            touch-action: manipulation;
        }

        .icon-btn:active {
            transform: scale(0.9);
        }

        /* 结算样式 */
        .settlement-item {
            background: rgba(255, 255, 255, 0.7);
            border-radius: 15px;
            padding: 18px;
            margin-bottom: 15px;
            border-left: 5px solid #43cea2;
            transition: all 0.3s;
            animation: fadeIn 0.5s;
        }

        .settlement-item.owe {
            border-left-color: #ff9a9e;
        }

        .settlement-item.receive {
            border-left-color: #43cea2;
        }

        /* 图表容器 */
        .chart-container {
            margin: 25px 0;
            height: 200px;
            position: relative;
            background: rgba(255, 255, 255, 0.5);
            border-radius: 15px;
            padding: 15px;
            border: 1px solid rgba(225, 232, 237, 0.5);
            overflow-x: auto;
            -webkit-overflow-scrolling: touch;
        }

        .chart-bars {
            display: flex;
            align-items: flex-end;
            justify-content: space-around;
            height: 150px;
            min-width: 100%;
            padding: 0 10px;
        }

        .chart-bar-wrapper {
            flex: 1;
            display: flex;
            flex-direction: column;
            align-items: center;
            min-width: 60px;
            margin: 0 5px;
        }

        .chart-bar {
            width: 100%;
            max-width: 50px;
            background: linear-gradient(to top, #43cea2, #185a9d);
            border-radius: 8px 8px 0 0;
            transition: all 0.5s;
            display: flex;
            align-items: flex-end;
            justify-content: center;
            color: white;
            font-size: 11px;
            font-weight: 500;
            padding-top: 5px;
            min-height: 20px;
        }

        .chart-label {
            font-size: 12px;
            color: #5a7a9a;
            margin-top: 8px;
            text-align: center;
            word-break: break-all;
        }

        /* 模态框 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 1000;
            backdrop-filter: blur(5px);
            overflow-y: auto;
            -webkit-overflow-scrolling: touch;
        }

        .modal-content {
            background: rgba(255, 255, 255, 0.95);
            width: 90%;
            max-width: 500px;
            margin: 50px auto;
            border-radius: 20px;
            padding: 25px;
            animation: slideIn 0.3s;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.2);
            border: 1px solid rgba(255, 255, 255, 0.5);
        }

        @keyframes slideIn {
            from {
                transform: translateY(-50px);
                opacity: 0;
            }
            to {
                transform: translateY(0);
                opacity: 1;
            }
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 25px;
        }

        .close-modal {
            background: none;
            border: none;
            font-size: 28px;
            cursor: pointer;
            color: #8a9ba8;
            transition: all 0.3s;
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            touch-action: manipulation;
        }

        .close-modal:active {
            background: rgba(225, 232, 237, 0.5);
        }

        /* 底部导航 */
        .bottom-nav {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            box-shadow: 0 -5px 20px rgba(0, 0, 0, 0.1);
            display: flex;
            justify-content: space-around;
            padding: 8px 0;
            z-index: 999;
            border-top: 1px solid rgba(225, 232, 237, 0.5);
        }

        .nav-item {
            flex: 1;
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 8px;
            cursor: pointer;
            transition: all 0.3s;
            color: #8a9ba8;
            text-decoration: none;
            font-size: 12px;
            border-radius: 10px;
            margin: 0 5px;
        }

        .nav-item.active {
            color: #185a9d;
            background: rgba(24, 90, 157, 0.1);
        }

        .nav-item:active {
            transform: scale(0.95);
        }

        .nav-icon {
            font-size: 20px;
            margin-bottom: 2px;
        }

        /* 浮动按钮 */
        .floating-btn {
            position: fixed;
            bottom: 90px;
            right: 20px;
            width: 56px;
            height: 56px;
            background: linear-gradient(135deg, #43cea2 0%, #185a9d 100%);
            color: white;
            border: none;
            border-radius: 50%;
            font-size: 24px;
            cursor: pointer;
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
            transition: all 0.3s;
            z-index: 100;
            display: flex;
            align-items: center;
            justify-content: center;
            touch-action: manipulation;
        }

        .floating-btn:active {
            transform: scale(0.95);
        }

        /* 提示信息 */
        .toast {
            position: fixed;
            bottom: 90px;
            left: 50%;
            transform: translateX(-50%);
            background: rgba(24, 90, 157, 0.9);
            color: white;
            padding: 12px 20px;
            border-radius: 12px;
            display: none;
            animation: slideUp 0.3s;
            z-index: 2000;
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.3);
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
            font-weight: 500;
            max-width: 90%;
            text-align: center;
        }

        @keyframes slideUp {
            from {
                transform: translateX(-50%) translateY(100px);
                opacity: 0;
            }
            to {
                transform: translateX(-50%) translateY(0);
                opacity: 1;
            }
        }

        /* 数据管理面板 */
        .data-actions {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
            gap: 15px;
            margin-top: 20px;
        }

        /* 空状态 */
        .empty-state {
            text-align: center;
            padding: 40px;
            color: #8a9ba8;
        }

        .empty-state svg {
            width: 80px;
            height: 80px;
            margin-bottom: 20px;
            opacity: 0.5;
            stroke: #a1c4fd;
        }

        /* 加载动画 */
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #185a9d;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* 份数输入控件样式 */
        .participant-item {
            display: flex;
            align-items: center;
            padding: 10px;
            margin-bottom: 8px;
            background: #f9f9f9;
            border-radius: 8px;
            border: 1px solid #e1e8ed;
        }

        .participant-checkbox {
            margin-right: 10px;
        }

        .participant-name {
            flex: 1;
            font-weight: 500;
        }

        .shares-input-wrapper {
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .shares-input {
            width: 60px !important;
            padding: 8px !important;
            text-align: center;
            font-size: 14px !important;
        }

        .shares-input-label {
            font-size: 12px;
            color: #666;
            white-space: nowrap;
        }

        /* 支出详情中的份数显示 */
        .expense-participants {
            font-size: 13px;
            color: #666;
            margin-top: 5px;
        }

        .participant-share {
            display: inline-block;
            background: #e3f2fd;
            padding: 2px 6px;
            border-radius: 4px;
            margin-right: 5px;
            margin-bottom: 3px;
        }

        /* 响应式设计 */
        @media (max-width: 600px) {
            .container {
                padding: 10px;
            }

            .header {
                padding: 20px 15px;
                border-radius: 15px;
            }

            .card {
                padding: 20px;
                border-radius: 15px;
            }

            .modal-content {
                width: 95%;
                margin: 20px auto;
                padding: 20px;
            }

            .stats-grid {
                grid-template-columns: repeat(2, 1fr);
                gap: 12px;
            }

            .stat-card {
                padding: 15px;
            }

            .stat-value {
                font-size: 20px;
            }

            .chart-container {
                height: 180px;
            }

            .chart-bars {
                height: 130px;
            }

            .chart-bar-wrapper {
                min-width: 50px;
            }
        }

        @media (max-width: 400px) {
            .stats-grid {
                grid-template-columns: 1fr;
            }
            
            .expense-item {
                flex-direction: column;
                align-items: flex-start;
            }
            
            .expense-actions {
                margin-top: 15px;
                align-self: flex-end;
            }
        }

        /* 打印样式优化 */
        @media print {
            .bottom-nav, .floating-btn, .modal {
                display: none !important;
            }
            
            .card {
                box-shadow: none !important;
                border: 1px solid #ddd !important;
                break-inside: avoid;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 头部 -->
        <div class="header">
            <div class="header-content">
                <h1>🧳 AA旅游记账本 Pro</h1>
                <p>轻松管理多趟旅行，智能分摊费用</p>
                <select class="trip-selector" id="tripSelector" onchange="TravelApp.switchTrip()">
                    <option value="">选择或创建旅行计划</option>
                </select>
            </div>
        </div>

        <!-- 统计卡片 -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-value" id="totalExpense">¥0.00</div>
                <div class="stat-label">总支出</div>
            </div>
            <div class="stat-card">
                <div class="stat-value" id="avgExpense">¥0.00</div>
                <div class="stat-label">人均支出</div>
            </div>
            <div class="stat-card">
                <div class="stat-value" id="memberCount">0</div>
                <div class="stat-label">参与人数</div>
            </div>
            <div class="stat-card">
                <div class="stat-value" id="expenseCount">0</div>
                <div class="stat-label">支出笔数</div>
            </div>
        </div>

        <!-- 当前出行信息 -->
        <div class="card" id="tripInfoCard" style="display: none;">
            <h3>📍 当前出行信息</h3>
            <div class="form-group">
                <label>出行名称</label>
                <input type="text" id="tripName" placeholder="例如：北京三日游">
            </div>
            <div class="form-group">
                <label>出行日期</label>
                <input type="date" id="tripDate">
            </div>
            <div class="form-group">
                <label>参与成员</label>
                <div style="display: flex; gap: 10px;">
                    <input type="text" id="memberInput" placeholder="输入成员姓名">
                    <button class="btn btn-secondary btn-small" onclick="TravelApp.addMember()" style="width: auto;">添加</button>
                </div>
                <div class="member-list" id="memberList"></div>
            </div>
            <button class="btn btn-danger" onclick="TravelApp.deleteCurrentTrip()" style="margin-top: 10px;">删除当前旅行</button>
        </div>

        <!-- 支出列表 -->
        <div class="card" id="expenseCard" style="display: none;">
            <h3>💰 支出记录</h3>
            <div class="expense-list" id="expenseList">
                <div class="empty-state">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 14l6-6m-5.5.5h.01m4.99 5h.01M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16l3.5-2 3.5 2 3.5-2 3.5 2z" />
                    </svg>
                    <p>暂无支出记录</p>
                </div>
            </div>
        </div>

        <!-- 结算信息 -->
        <div class="card" id="settlementCard" style="display: none;">
            <h3>🧮 费用结算</h3>
            <div class="summary">
                <div class="summary-item">
                    <span>总支出：</span>
                    <span id="summaryTotal">¥0.00</span>
                </div>
                <div class="summary-item">
                    <span>人均费用：</span>
                    <span id="summaryAvg">¥0.00</span>
                </div>
                <div class="summary-total">
                    <span>结算结果：</span>
                </div>
            </div>
            <div id="settlementList">
                <div class="empty-state">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                    <p>暂无结算信息</p>
                </div>
            </div>
        </div>

        <!-- 图表分析 -->
        <div class="card" id="chartCard" style="display: none;">
            <h3>📊 支出分析</h3>
            <div class="chart-container" id="chartContainer">
                <div class="empty-state">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
                    </svg>
                    <p>暂无数据</p>
                </div>
            </div>
        </div>

        <!-- 数据管理 -->
        <div class="card" id="dataCard" style="display: none;">
            <h3>💾 数据管理</h3>
            <div class="settings-section">
                <h4 class="settings-title">📤 导出数据</h4>
                <p style="color: #8a9ba8; font-size: 14px; margin-bottom: 15px;">将当前旅行数据导出为JSON文件</p>
                <button class="btn btn-secondary" onclick="TravelApp.exportCurrentTrip()">导出当前旅行</button>
                <button class="btn btn-secondary" onclick="TravelApp.exportAllTrips()">导出所有旅行</button>
            </div>
            
            <div class="settings-section">
                <h4 class="settings-title">📥 导入数据</h4>
                <p style="color: #8a9ba8; font-size: 14px; margin-bottom: 15px;">从JSON文件导入旅行数据</p>
                <div class="file-input-wrapper">
                    <input type="file" id="importFile" accept="application/json" onchange="TravelApp.importData(this)">
                    <label for="importFile" class="file-input-label">选择文件导入</label>
                </div>
            </div>
            
            <div class="settings-section">
                <h4 class="settings-title">🗑️ 数据清理</h4>
                <p style="color: #8a9ba8; font-size: 14px; margin-bottom: 15px;">谨慎操作，删除后无法恢复</p>
                <button class="btn btn-danger" onclick="TravelApp.clearAllData()">清空所有数据</button>
            </div>
        </div>
    </div>

    <!-- 底部导航 -->
    <nav class="bottom-nav" id="bottomNav" style="display: none;">
        <a class="nav-item active" onclick="TravelApp.showSection('tripInfo')">
            <span class="nav-icon">📍</span>
            <span>旅行信息</span>
        </a>
        <a class="nav-item" onclick="TravelApp.showSection('expenses')">
            <span class="nav-icon">💰</span>
            <span>支出记录</span>
        </a>
        <a class="nav-item" onclick="TravelApp.showSection('settlement')">
            <span class="nav-icon">🧮</span>
            <span>费用结算</span>
        </a>
        <a class="nav-item" onclick="TravelApp.showSection('chart')">
            <span class="nav-icon">📊</span>
            <span>数据分析</span>
        </a>
        <a class="nav-item" onclick="TravelApp.showSection('data')">
            <span class="nav-icon">💾</span>
            <span>数据管理</span>
        </a>
    </nav>

    <!-- 添加支出按钮 -->
    <button class="floating-btn" id="addExpenseBtn" onclick="TravelApp.showAddExpenseModal()" style="display: none;">+</button>

    <!-- 添加支出模态框 -->
    <div class="modal" id="addExpenseModal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>添加支出</h2>
                <button class="close-modal" onclick="TravelApp.closeModal('addExpenseModal')">&times;</button>
            </div>
            <form id="expenseForm">
                <div class="form-group">
                    <label>支出金额 (元)</label>
                    <input type="number" id="expenseAmount" step="0.01" min="0.01" required>
                </div>
                <div class="form-group">
                    <label>支出描述</label>
                    <input type="text" id="expenseDescription" placeholder="例如：午餐、门票、住宿..." required>
                </div>
                <div class="form-group">
                    <label>支出人</label>
                    <select id="expensePayer" required>
                        <option value="">请选择支出人</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>参与分摊的成员（可设置份数）</label>
                    <div id="expenseMembers"></div>
                    <p style="font-size: 12px; color: #999; margin-top: 8px;">默认为1份，可按实际调整（如儿童算0.5份）</p>
                </div>
                <button type="submit" class="btn">添加支出</button>
            </form>
        </div>
    </div>

    <!-- 编辑支出模态框 -->
    <div class="modal" id="editExpenseModal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>编辑支出</h2>
                <button class="close-modal" onclick="TravelApp.closeModal('editExpenseModal')">&times;</button>
            </div>
            <form id="editExpenseForm">
                <input type="hidden" id="editExpenseId">
                <div class="form-group">
                    <label>支出金额 (元)</label>
                    <input type="number" id="editExpenseAmount" step="0.01" min="0.01" required>
                </div>
                <div class="form-group">
                    <label>支出描述</label>
                    <input type="text" id="editExpenseDescription" required>
                </div>
                <div class="form-group">
                    <label>支出人</label>
                    <select id="editExpensePayer" required>
                        <option value="">请选择支出人</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>参与分摊的成员（可设置份数）</label>
                    <div id="editExpenseMembers"></div>
                    <p style="font-size: 12px; color: #999; margin-top: 8px;">默认为1份，可按实际调整（如儿童算0.5份）</p>
                </div>
                <button type="submit" class="btn">保存修改</button>
            </form>
        </div>
    </div>

    <!-- 旅行管理模态框 -->
    <div class="modal" id="tripManagerModal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>🗺️ 旅行管理</h2>
                <button class="close-modal" onclick="TravelApp.closeModal('tripManagerModal')">&times;</button>
            </div>
            <div class="modal-tabs">
                <button class="modal-tab active" onclick="TravelApp.switchTab('tripList')">现有旅行</button>
                <button class="modal-tab" onclick="TravelApp.switchTab('newTrip')">创建新旅行</button>
            </div>
            
            <div class="modal-tab-content active" id="tripListTab">
                <div class="trip-list" id="allTripsList"></div>
            </div>
            
            <div class="modal-tab-content" id="newTripTab">
                <form id="newTripForm">
                    <div class="form-group">
                        <label>旅行名称</label>
                        <input type="text" id="newTripName" placeholder="例如：云南七日游" required>
                    </div>
                    <div class="form-group">
                        <label>旅行日期</label>
                        <input type="date" id="newTripDate" required>
                    </div>
                    <button type="submit" class="btn">创建旅行</button>
                </form>
            </div>
        </div>
    </div>

    <!-- 提示信息 -->
    <div class="toast" id="toast"></div>

    <script>
        // 应用常量配置
        const CONFIG = {
            STORAGE_KEY: 'travelAppData',
            AUTO_SAVE_DELAY: 1000,
            DEBOUNCE_DELAY: 300,
            MAX_MEMBERS: 20,
            MAX_EXPENSES: 1000,
            DATA_VERSION: 2
        };

        // 工具函数
        const Utils = {
            // 防抖函数
            debounce: (func, wait) => {
                let timeout;
                return function executedFunction(...args) {
                    const later = () => {
                        clearTimeout(timeout);
                        func(...args);
                    };
                    clearTimeout(timeout);
                    timeout = setTimeout(later, wait);
                };
            },

            // 格式化货币
            formatCurrency: (amount) => `¥${amount.toFixed(2)}`,

            // 生成唯一ID
            generateId: () => Date.now() + Math.random().toString(36).substr(2, 9),

            // 验证数字
            validateNumber: (value, min = 0, max = Infinity) => {
                const num = parseFloat(value);
                return !isNaN(num) && num >= min && num <= max;
            },

            // 深拷贝
            deepClone: (obj) => JSON.parse(JSON.stringify(obj)),

            // 安全数据操作
            safeOperation: (operation, errorMessage = '操作失败') => {
                try {
                    return operation();
                } catch (error) {
                    console.error(errorMessage, error);
                    TravelApp.showToast(errorMessage);
                    return null;
                }
            }
        };

        // 数据验证器
        const Validators = {
            validateExpense: (expense) => {
                const errors = [];
                if (!Utils.validateNumber(expense.amount, 0.01)) {
                    errors.push('金额必须大于0');
                }
                if (!expense.description?.trim()) {
                    errors.push('描述不能为空');
                }
                if (!expense.payer) {
                    errors.push('必须选择支出人');
                }
                if (!expense.participants?.length) {
                    errors.push('必须选择分摊成员');
                }
                return errors;
            },
            
            validateTrip: (trip) => {
                const errors = [];
                if (!trip.name?.trim()) {
                    errors.push('旅行名称不能为空');
                }
                if (!trip.date) {
                    errors.push('旅行日期不能为空');
                }
                return errors;
            }
        };

        // 主应用对象
        const TravelApp = {
            // 全局数据
            data: {
                currentTripId: null,
                trips: []
            },

            currentSection: 'tripInfo',
            autoSaveTimer: null,

            // 初始化应用
            init: function() {
                this.loadAllData();
                this.initializeApp();
                document.getElementById('tripDate').value = new Date().toISOString().split('T')[0];
                document.getElementById('newTripDate').value = new Date().toISOString().split('T')[0];
                
                // 添加事件监听
                this.setupEventListeners();
                
                // 增强键盘导航
                this.enhanceKeyboardNavigation();
                
                // 设置自动保存
                this.setupAutoSave();
                
                console.log('AA旅游记账本 Pro 初始化完成');
            },

            // 设置事件监听
            setupEventListeners: function() {
                // 支出表单提交
                document.getElementById('expenseForm').addEventListener('submit', (e) => {
                    e.preventDefault();
                    this.handleAddExpense();
                });

                // 编辑支出表单提交
                document.getElementById('editExpenseForm').addEventListener('submit', (e) => {
                    e.preventDefault();
                    this.handleEditExpense();
                });

                // 新旅行表单提交
                document.getElementById('newTripForm').addEventListener('submit', (e) => {
                    e.preventDefault();
                    this.handleCreateTrip();
                });

                // 输入变化监听
                document.getElementById('tripName').addEventListener('input', () => {
                    this.updateTripInfo();
                });

                document.getElementById('tripDate').addEventListener('input', () => {
                    this.updateTripInfo();
                });

                document.getElementById('memberInput').addEventListener('keypress', (e) => {
                    if (e.key === 'Enter') {
                        this.addMember();
                    }
                });

                // 点击模态框外部关闭
                window.addEventListener('click', (e) => {
                    if (e.target.classList.contains('modal')) {
                        e.target.style.display = 'none';
                    }
                });

                // 页面卸载前保存
                window.addEventListener('beforeunload', () => {
                    this.saveAllData();
                });

                // 触摸手势支持
                this.setupTouchGestures();
            },

            // 设置触摸手势
            setupTouchGestures: function() {
                let touchStartX = 0;
                let touchEndX = 0;

                document.addEventListener('touchstart', (e) => {
                    touchStartX = e.changedTouches[0].screenX;
                });

                document.addEventListener('touchend', (e) => {
                    touchEndX = e.changedTouches[0].screenX;
                    this.handleSwipe(touchStartX, touchEndX);
                });
            },

            // 处理滑动
            handleSwipe: function(startX, endX) {
                const swipeThreshold = 100;
                const diff = startX - endX;
                
                if (Math.abs(diff) > swipeThreshold) {
                    const sections = ['tripInfo', 'expenses', 'settlement', 'chart', 'data'];
                    const currentIndex = sections.indexOf(this.currentSection);
                    
                    if (diff > 0) {
                        // 左滑 - 下一个
                        const nextIndex = (currentIndex + 1) % sections.length;
                        this.showSection(sections[nextIndex]);
                    } else {
                        // 右滑 - 上一个
                        const prevIndex = (currentIndex - 1 + sections.length) % sections.length;
                        this.showSection(sections[prevIndex]);
                    }
                }
            },

            // 设置自动保存
            setupAutoSave: function() {
                const autoSave = Utils.debounce(() => {
                    if (this.data.currentTripId) {
                        this.saveAllData();
                    }
                }, CONFIG.AUTO_SAVE_DELAY);

                document.addEventListener('input', autoSave);
                document.addEventListener('change', autoSave);
            },

            // 增强键盘导航
            enhanceKeyboardNavigation: function() {
                document.addEventListener('keydown', (e) => {
                    // 必须结合Ctrl键
                    if (!e.ctrlKey) return;
                    
                    switch(e.key) {
                        case 'a':
                            e.preventDefault();
                            if (this.data.currentTripId) {
                                this.showAddExpenseModal();
                            }
                            break;
                        case 'e':
                            e.preventDefault();
                            if (this.data.currentTripId) {
                                this.exportCurrentTrip();
                            }
                            break;
                        case 'p':
                            e.preventDefault();
                            if (this.data.currentTripId) {
                                this.printReport();
                            }
                            break;
                        case 'n':
                            e.preventDefault();
                            this.showTripManager();
                            break;
                        case 's':
                            e.preventDefault();
                            if (this.data.currentTripId) {
                                this.saveAllData();
                                this.showToast('数据已保存');
                            }
                            break;
                    }

                    // ESC键关闭模态框
                    if (e.key === 'Escape') {
                        const openModal = document.querySelector('.modal[style*="display: block"]');
                        if (openModal) {
                            this.closeModal(openModal.id);
                        }
                    }
                    
                    // Enter键在输入框时快速提交
                    if (e.key === 'Enter' && e.ctrlKey) {
                        const focused = document.activeElement;
                        if (focused.form) {
                            focused.form.dispatchEvent(new Event('submit'));
                        }
                    }
                });
            },

            // 加载所有数据
            loadAllData: function() {
                return Utils.safeOperation(() => {
                    const saved = localStorage.getItem(CONFIG.STORAGE_KEY);
                    if (saved) {
                        const data = JSON.parse(saved);
                        this.data = this.migrateData(data);
                    }
                }, '数据加载失败') || { currentTripId: null, trips: [] };
            },

            // 数据迁移
            migrateData: function(data) {
                if (!data.version || data.version < CONFIG.DATA_VERSION) {
                    // 从版本1迁移到版本2
                    if (!data.version) {
                        data.version = 1;
                    }
                    
                    if (data.version === 1) {
                        // 迁移逻辑
                        data.trips.forEach(trip => {
                            if (trip.expenses) {
                                trip.expenses.forEach(expense => {
                                    if (expense.participants && typeof expense.participants[0] === 'string') {
                                        expense.participants = expense.participants.map(name => ({
                                            name: name,
                                            shares: 1
                                        }));
                                    }
                                });
                            }
                        });
                        data.version = CONFIG.DATA_VERSION;
                    }
                }
                return data;
            },

            // 保存所有数据
            saveAllData: function() {
                Utils.safeOperation(() => {
                    localStorage.setItem(CONFIG.STORAGE_KEY, JSON.stringify(this.data));
                }, '数据保存失败');
            },

            // 获取当前旅行数据
            getCurrentTrip: function() {
                if (!this.data.currentTripId) return null;
                return this.data.trips.find(t => t.id === this.data.currentTripId);
            },

            // 初始化应用
            initializeApp: function() {
                this.updateTripSelector();
                if (this.data.currentTripId) {
                    this.showSection('tripInfo');
                    this.updateUI();
                }
            },

            // 更新旅行选择器
            updateTripSelector: function() {
                const selector = document.getElementById('tripSelector');
                selector.innerHTML = '<option value="">选择或创建旅行计划</option>';
                
                this.data.trips.forEach(trip => {
                    const option = document.createElement('option');
                    option.value = trip.id;
                    option.textContent = `${trip.name} (${trip.date})`;
                    if (trip.id === this.data.currentTripId) {
                        option.selected = true;
                    }
                    selector.appendChild(option);
                });
                
                // 添加管理选项
                const manageOption = document.createElement('option');
                manageOption.value = 'manage';
                manageOption.textContent = '➕ 管理旅行计划...';
                selector.appendChild(manageOption);
            },

            // 切换旅行
            switchTrip: function() {
                const selector = document.getElementById('tripSelector');
                const value = selector.value;
                
                if (value === 'manage') {
                    this.showTripManager();
                    selector.value = this.data.currentTripId || '';
                    return;
                }
                
                if (value) {
                    this.data.currentTripId = value;
                    this.saveAllData();
                    this.showSection('tripInfo');
                    this.updateUI();
                }
            },

            // 显示旅行管理器
            showTripManager: function() {
                this.updateAllTripsList();
                document.getElementById('tripManagerModal').style.display = 'block';
            },

            // 更新所有旅行列表
            updateAllTripsList: function() {
                const list = document.getElementById('allTripsList');
                
                if (this.data.trips.length === 0) {
                    list.innerHTML = '<div class="empty-state">暂无旅行记录</div>';
                    return;
                }
                
                list.innerHTML = '';
                this.data.trips.forEach(trip => {
                    const item = document.createElement('div');
                    item.className = `trip-item ${trip.id === this.data.currentTripId ? 'active' : ''}`;
                    
                    const expenseCount = trip.expenses ? trip.expenses.length : 0;
                    const totalExpense = trip.expenses ? 
                        trip.expenses.reduce((sum, e) => sum + e.amount, 0) : 0;
                    
                    item.innerHTML = `
                        <div class="trip-info">
                            <h4>${trip.name}</h4>
                            <div class="trip-meta">${trip.date} · ${expenseCount}笔支出 · ¥${totalExpense.toFixed(2)}</div>
                        </div>
                        <div class="trip-actions">
                            <button class="icon-btn" onclick="TravelApp.switchToTrip('${trip.id}')" title="切换">
                                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                                </svg>
                            </button>
                            <button class="icon-btn" onclick="TravelApp.deleteTrip('${trip.id}')" title="删除">
                                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                </svg>
                            </button>
                        </div>
                    `;
                    list.appendChild(item);
                });
            },

            // 切换到指定旅行
            switchToTrip: function(tripId) {
                this.data.currentTripId = tripId;
                this.saveAllData();
                this.updateTripSelector();
                this.updateUI();
                this.closeModal('tripManagerModal');
                this.showToast('已切换旅行计划');
            },

            // 创建新旅行
            handleCreateTrip: function() {
                const name = document.getElementById('newTripName').value.trim();
                const date = document.getElementById('newTripDate').value;
                
                if (!name || !date) {
                    this.showToast('请填写完整信息');
                    return;
                }
                
                const newTrip = {
                    id: Utils.generateId(),
                    name: name,
                    date: date,
                    members: [],
                    expenses: []
                };
                
                this.data.trips.push(newTrip);
                this.data.currentTripId = newTrip.id;
                this.saveAllData();
                
                this.updateTripSelector();
                this.updateUI();
                this.closeModal('tripManagerModal');
                
                document.getElementById('newTripName').value = '';
                document.getElementById('newTripDate').value = new Date().toISOString().split('T')[0];
                
                this.showToast('旅行计划创建成功');
            },

            // 删除旅行
            deleteTrip: function(tripId) {
                const trip = this.data.trips.find(t => t.id === tripId);
                if (!trip) return;
                
                if (!confirm(`确定要删除旅行"${trip.name}"吗？所有相关数据将被清除！`)) {
                    return;
                }
                
                this.data.trips = this.data.trips.filter(t => t.id !== tripId);
                
                if (this.data.currentTripId === tripId) {
                    this.data.currentTripId = this.data.trips.length > 0 ? this.data.trips[0].id : null;
                }
                
                this.saveAllData();
                this.updateTripSelector();
                this.updateUI();
                this.updateAllTripsList();
                
                this.showToast('旅行计划已删除');
            },

            // 删除当前旅行
            deleteCurrentTrip: function() {
                if (!this.data.currentTripId) {
                    this.showToast('当前没有选中的旅行');
                    return;
                }
                
                this.deleteTrip(this.data.currentTripId);
            },

            // 显示指定区域
            showSection: function(section) {
                this.currentSection = section;
                
                // 隐藏所有区域
                const sections = ['tripInfoCard', 'expenseCard', 'settlementCard', 'chartCard', 'dataCard'];
                sections.forEach(id => {
                    document.getElementById(id).style.display = 'none';
                });
                
                // 显示指定区域
                const sectionMap = {
                    'tripInfo': 'tripInfoCard',
                    'expenses': 'expenseCard',
                    'settlement': 'settlementCard',
                    'chart': 'chartCard',
                    'data': 'dataCard'
                };
                
                if (sectionMap[section]) {
                    document.getElementById(sectionMap[section]).style.display = 'block';
                }
                
                // 更新底部导航
                const navItems = document.querySelectorAll('.nav-item');
                navItems.forEach(item => item.classList.remove('active'));
                
                if (section === 'tripInfo') navItems[0].classList.add('active');
                if (section === 'expenses') navItems[1].classList.add('active');
                if (section === 'settlement') navItems[2].classList.add('active');
                if (section === 'chart') navItems[3].classList.add('active');
                if (section === 'data') navItems[4].classList.add('active');
                
                // 显示/隐藏添加按钮
                document.getElementById('addExpenseBtn').style.display = 
                    (section === 'expenses' && this.data.currentTripId) ? 'flex' : 'none';
                
                // 显示底部导航
                document.getElementById('bottomNav').style.display = 
                    this.data.currentTripId ? 'flex' : 'none';
                
                // 更新图表
                if (section === 'chart') {
                    this.updateChart();
                }
            },

            // 切换模态框标签
            switchTab: function(tabName) {
                const tabs = document.querySelectorAll('.modal-tab');
                const contents = document.querySelectorAll('.modal-tab-content');
                
                tabs.forEach(tab => tab.classList.remove('active'));
                contents.forEach(content => content.classList.remove('active'));
                
                if (tabName === 'tripList') {
                    tabs[0].classList.add('active');
                    document.getElementById('tripListTab').classList.add('active');
                } else if (tabName === 'newTrip') {
                    tabs[1].classList.add('active');
                    document.getElementById('newTripTab').classList.add('active');
                }
            },

            // 显示提示信息
            showToast: function(message, duration = 3000) {
                const toast = document.getElementById('toast');
                toast.textContent = message;
                toast.style.display = 'block';
                
                setTimeout(() => {
                    toast.style.display = 'none';
                }, duration);
            },

            // 添加成员
            addMember: function() {
                const trip = this.getCurrentTrip();
                if (!trip) {
                    this.showToast('请先创建或选择旅行计划');
                    return;
                }
                
                const input = document.getElementById('memberInput');
                const name = input.value.trim();
                
                if (!name) {
                    this.showToast('请输入成员姓名');
                    return;
                }
                
                if (trip.members.includes(name)) {
                    this.showToast('该成员已存在');
                    return;
                }
                
                trip.members.push(name);
                this.saveAllData();
                this.updateUI();
                input.value = '';
                this.showToast('成员添加成功');
            },

            // 删除成员
            removeMember: function(name) {
                const trip = this.getCurrentTrip();
                if (!trip) return;
                
                // 检查是否有相关支出
                const hasExpense = trip.expenses.some(e => e.payer === name || 
                    e.participants.some(p => p.name === name));
                if (hasExpense) {
                    this.showToast('该成员有关联支出，无法删除');
                    return;
                }
                
                trip.members = trip.members.filter(m => m !== name);
                this.saveAllData();
                this.updateUI();
                this.showToast('成员删除成功');
            },

            // 显示添加支出模态框
            showAddExpenseModal: function() {
                const trip = this.getCurrentTrip();
                if (!trip || trip.members.length === 0) {
                    this.showToast('请先添加成员');
                    return;
                }
                
                this.updateExpenseModal('add');
                document.getElementById('addExpenseModal').style.display = 'block';
            },

            // 更新支出模态框（支持份数设置）
            // 更新支出模态框（支持份数设置）
            updateExpenseModal: function(type) {
                const trip = this.getCurrentTrip();
                if (!trip) return;
                
                let payerSelect, membersDiv;
                if (type === 'add') {
                    payerSelect = document.getElementById('expensePayer');
                    membersDiv = document.getElementById('expenseMembers');
                } else {
                    payerSelect = document.getElementById('editExpensePayer');
                    membersDiv = document.getElementById('editExpenseMembers');
                }
                
                // 清空选项
                payerSelect.innerHTML = '<option value="">请选择支出人</option>';
                membersDiv.innerHTML = '';
                
                // 添加成员选项
                trip.members.forEach(member => {
                    // 支出人选项
                    const option = document.createElement('option');
                    option.value = member;
                    option.textContent = member;
                    payerSelect.appendChild(option);
                    
                    // 分摊成员复选框和份数输入
                    const item = document.createElement('div');
                    item.className = 'participant-item';
                    
                    const checkboxId = `${type}_participant_${member}`;
                    item.innerHTML = `
                        <input type="checkbox" id="${checkboxId}" name="${type}ExpenseParticipants" value="${member}" 
                               class="participant-checkbox" checked onchange="TravelApp.toggleSharesInput('${type}', '${member}')">
                        <label for="${checkboxId}" class="participant-name">${member}</label>
                        <div class="shares-input-wrapper">
                            <span class="shares-input-label">份数：</span>
                            <input type="number" id="${type}_shares_${member}" name="${type}ExpenseShares" 
                                   data-member="${member}" value="1" min="0.1" max="10" step="0.1"
                                   class="shares-input" required>
                        </div>
                    `;
                    
                    membersDiv.appendChild(item);
                });
            },

            // 切换份数输入框的禁用状态
            toggleSharesInput: function(type, member) {
                const checkbox = document.querySelector(`input[name="${type}ExpenseParticipants"][value="${member}"]`);
                const sharesInput = document.querySelector(`input[name="${type}ExpenseShares"][data-member="${member}"]`);
                if (checkbox && sharesInput) {
                    sharesInput.disabled = !checkbox.checked;
                    if (!checkbox.checked) {
                        sharesInput.value = 0;
                    } else if (sharesInput.value == 0) {
                        sharesInput.value = 1;
                    }
                }
            },

            // 关闭模态框
            closeModal: function(modalId) {
                document.getElementById(modalId).style.display = 'none';
            },

            // 处理添加支出
            handleAddExpense: function() {
                const trip = this.getCurrentTrip();
                if (!trip) return;
                
                const amount = parseFloat(document.getElementById('expenseAmount').value);
                const description = document.getElementById('expenseDescription').value;
                const payer = document.getElementById('expensePayer').value;
                
                // 获取参与者和份数
                const participants = [];
                const checkboxes = document.querySelectorAll('input[name="addExpenseParticipants"]:checked');
                
                checkboxes.forEach(cb => {
                    const member = cb.value;
                    const sharesInput = document.querySelector(`input[name="addExpenseShares"][data-member="${member}"]`);
                    const shares = parseFloat(sharesInput.value) || 1;
                    
                    if (shares > 0) {
                        participants.push({
                            name: member,
                            shares: shares
                        });
                    }
                });
                
                if (!payer) {
                    this.showToast('请选择支出人');
                    return;
                }
                
                if (participants.length === 0) {
                    this.showToast('请选择至少一位参与分摊的成员');
                    return;
                }
                
                if (amount <= 0) {
                    this.showToast('请输入有效金额');
                    return;
                }
                
                // 验证份数有效性
                const totalShares = participants.reduce((sum, p) => sum + p.shares, 0);
                if (totalShares <= 0) {
                    this.showToast('总份数必须大于0');
                    return;
                }
                
                const expense = {
                    id: Date.now(),
                    amount: amount,
                    description: description,
                    payer: payer,
                    participants: participants,
                    date: new Date().toLocaleString('zh-CN')
                };
                
                trip.expenses.push(expense);
                this.saveAllData();
                this.updateUI();
                this.closeModal('addExpenseModal');
                document.getElementById('expenseForm').reset();
                this.showToast('支出添加成功');
            },

            // 编辑支出 - 修复版本
            editExpense: function(id) {
                try {
                    const trip = this.getCurrentTrip();
                    if (!trip) return;
                    
                    const expense = trip.expenses.find(e => e.id === id);
                    if (!expense) return;
                    
                    document.getElementById('editExpenseId').value = id;
                    document.getElementById('editExpenseAmount').value = expense.amount;
                    document.getElementById('editExpenseDescription').value = expense.description;
                    
                    this.updateExpenseModal('edit');
                    
                    // 设置支出人
                    document.getElementById('editExpensePayer').value = expense.payer;
                    
                    // 等待DOM更新完成后再设置参与者状态
                    setTimeout(() => {
                        this.setEditExpenseParticipants(expense);
                    }, 50);
                    
                    document.getElementById('editExpenseModal').style.display = 'block';
                } catch (error) {
                    console.error('编辑支出时出错:', error);
                    this.showToast('编辑支出时发生错误，请重试');
                }
            },

            // 设置编辑支出模态框的参与者状态 - 修复版本
            setEditExpenseParticipants: function(expense) {
                try {
                    const checkboxes = document.querySelectorAll('input[name="editExpenseParticipants"]');
                    
                    checkboxes.forEach(cb => {
                        const member = cb.value;
                        const participant = expense.participants.find(p => p.name === member);
                        
                        if (participant) {
                            cb.checked = true;
                            // 使用更安全的选择器方式
                            const sharesInput = this.findSharesInput('edit', member);
                            if (sharesInput) {
                                sharesInput.value = participant.shares;
                                sharesInput.disabled = false;
                            }
                        } else {
                            cb.checked = false;
                            const sharesInput = this.findSharesInput('edit', member);
                            if (sharesInput) {
                                sharesInput.value = 0;
                                sharesInput.disabled = true;
                            }
                        }
                    });
                } catch (error) {
                    console.error('设置参与者状态时出错:', error);
                }
            },

            // 查找份数输入框 - 修复版本
            findSharesInput: function(type, member) {
                try {
                    // 使用更安全的选择器，避免特殊字符问题
                    const inputs = document.querySelectorAll(`input[name="${type}ExpenseShares"]`);
                    for (let input of inputs) {
                        if (input.getAttribute('data-member') === member) {
                            return input;
                        }
                    }
                    return null;
                } catch (error) {
                    console.error('查找份数输入框时出错:', error);
                    return null;
                }
            },

            // 处理编辑支出
            handleEditExpense: function() {
                const trip = this.getCurrentTrip();
                if (!trip) return;
                
                const id = parseInt(document.getElementById('editExpenseId').value);
                const expense = trip.expenses.find(e => e.id === id);
                
                if (!expense) return;
                
                const amount = parseFloat(document.getElementById('editExpenseAmount').value);
                const description = document.getElementById('editExpenseDescription').value;
                const payer = document.getElementById('editExpensePayer').value;
                
                // 获取参与者和份数
                const participants = [];
                const checkboxes = document.querySelectorAll('input[name="editExpenseParticipants"]:checked');
                
                checkboxes.forEach(cb => {
                    const member = cb.value;
                    const sharesInput = this.findSharesInput('edit', member);
                    const shares = sharesInput ? parseFloat(sharesInput.value) || 1 : 1;
                    
                    if (shares > 0) {
                        participants.push({
                            name: member,
                            shares: shares
                        });
                    }
                });
                
                if (!payer) {
                    this.showToast('请选择支出人');
                    return;
                }
                
                if (participants.length === 0) {
                    this.showToast('请选择至少一位参与分摊的成员');
                    return;
                }
                
                if (amount <= 0) {
                    this.showToast('请输入有效金额');
                    return;
                }
                
                // 验证份数有效性
                const totalShares = participants.reduce((sum, p) => sum + p.shares, 0);
                if (totalShares <= 0) {
                    this.showToast('总份数必须大于0');
                    return;
                }
                
                expense.amount = amount;
                expense.description = description;
                expense.payer = payer;
                expense.participants = participants;
                expense.date = new Date().toLocaleString('zh-CN');
                
                this.saveAllData();
                this.updateUI();
                this.closeModal('editExpenseModal');
                this.showToast('支出修改成功');
            },

            // 删除支出
            deleteExpense: function(id) {
                const trip = this.getCurrentTrip();
                if (!trip) return;
                
                if (!confirm('确定要删除这笔支出吗？')) return;
                
                trip.expenses = trip.expenses.filter(e => e.id !== id);
                this.saveAllData();
                this.updateUI();
                this.showToast('支出删除成功');
            },

            // 计算结算信息（支持份数）
            calculateSettlement: function() {
                const trip = this.getCurrentTrip();
                if (!trip) return {};
                
                const memberBalances = {};
                
                // 初始化成员余额
                trip.members.forEach(member => {
                    memberBalances[member] = 0;
                });
                
                // 计算每个人的支出和应分摊
                trip.expenses.forEach(expense => {
                    // 计算总份数
                    const totalShares = expense.participants.reduce((sum, p) => sum + (p.shares || 1), 0);
                    const perShareAmount = expense.amount / totalShares;
                    
                    // 支出人获得金额
                    memberBalances[expense.payer] += expense.amount;
                    
                    // 参与分摊的人按份数扣除金额
                    expense.participants.forEach(participant => {
                        const shares = participant.shares || 1;
                        memberBalances[participant.name] -= perShareAmount * shares;
                    });
                });
                
                return memberBalances;
            },

            // 生成结算建议
            generateSettlementSuggestions: function(balances) {
                const settlements = [];
                const members = Object.keys(balances);
                
                // 创建余额数组
                const balanceArray = members.map(member => ({
                    member: member,
                    balance: balances[member]
                }));
                
                // 按余额排序
                balanceArray.sort((a, b) => a.balance - b.balance);
                
                let i = 0;
                let j = balanceArray.length - 1;
                
                while (i < j) {
                    const debtor = balanceArray[i];
                    const creditor = balanceArray[j];
                    
                    if (Math.abs(debtor.balance) < 0.01 || Math.abs(creditor.balance) < 0.01) {
                        if (Math.abs(debtor.balance) < 0.01) i++;
                        if (Math.abs(creditor.balance) < 0.01) j--;
                        continue;
                    }
                    
                    const amount = Math.min(Math.abs(debtor.balance), creditor.balance);
                    
                    settlements.push({
                        from: debtor.member,
                        to: creditor.member,
                        amount: amount
                    });
                    
                    debtor.balance += amount;
                    creditor.balance -= amount;
                    
                    if (Math.abs(debtor.balance) < 0.01) i++;
                    if (Math.abs(creditor.balance) < 0.01) j--;
                }
                
                return settlements;
            },

            // 更新UI
            updateUI: function() {
                const trip = this.getCurrentTrip();
                
                if (!trip) {
                    // 隐藏所有内容
                    document.getElementById('bottomNav').style.display = 'none';
                    document.getElementById('addExpenseBtn').style.display = 'none';
                    document.getElementById('tripInfoCard').style.display = 'none';
                    document.getElementById('expenseCard').style.display = 'none';
                    document.getElementById('settlementCard').style.display = 'none';
                    document.getElementById('chartCard').style.display = 'none';
                    document.getElementById('dataCard').style.display = 'none';
                    return;
                }
                
                // 显示底部导航
                document.getElementById('bottomNav').style.display = 'flex';
                
                // 更新出行信息
                document.getElementById('tripName').value = trip.name || '';
                document.getElementById('tripDate').value = trip.date || '';
                
                // 更新成员列表
                const memberList = document.getElementById('memberList');
                memberList.innerHTML = '';
                trip.members.forEach(member => {
                    const tag = document.createElement('div');
                    tag.className = 'member-tag';
                    tag.innerHTML = `
                        ${member}
                        <span class="remove" onclick="TravelApp.removeMember('${member}')">&times;</span>
                    `;
                    memberList.appendChild(tag);
                });
                
                // 更新统计信息
                const totalExpense = trip.expenses.reduce((sum, e) => sum + e.amount, 0);
                const avgExpense = trip.members.length > 0 ? totalExpense / trip.members.length : 0;
                
                document.getElementById('totalExpense').textContent = Utils.formatCurrency(totalExpense);
                document.getElementById('avgExpense').textContent = Utils.formatCurrency(avgExpense);
                document.getElementById('memberCount').textContent = trip.members.length;
                document.getElementById('expenseCount').textContent = trip.expenses.length;
                
                // 更新支出列表
                const expenseList = document.getElementById('expenseList');
                if (trip.expenses.length === 0) {
                    expenseList.innerHTML = `
                        <div class="empty-state">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 14l6-6m-5.5.5h.01m4.99 5h.01M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16l3.5-2 3.5 2 3.5-2 3.5 2z" />
                            </svg>
                            <p>暂无支出记录</p>
                        </div>
                    `;
                } else {
                    expenseList.innerHTML = '';
                    trip.expenses.slice().reverse().forEach(expense => {
                        const item = document.createElement('div');
                        item.className = 'expense-item';
                        
                        // 生成参与者显示文本（含份数）
                        const participantsText = expense.participants.map(p => 
                            `${p.name}(${p.shares}份)`
                        ).join(', ');
                        
                        item.innerHTML = `
                            <div class="expense-info">
                                <div class="expense-amount">${Utils.formatCurrency(expense.amount)}</div>
                                <div class="expense-description">${expense.description}</div>
                                <div class="expense-date">${expense.payer} · ${expense.date}</div>
                                <div class="expense-participants">分摊：${participantsText}</div>
                            </div>
                            <div class="expense-actions">
                                <button class="icon-btn" onclick="TravelApp.editExpense(${expense.id})" title="编辑">
                                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                                    </svg>
                                </button>
                                <button class="icon-btn" onclick="TravelApp.deleteExpense(${expense.id})" title="删除">
                                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                    </svg>
                                </button>
                            </div>
                        `;
                        expenseList.appendChild(item);
                    });
                }
                
                // 更新结算信息
                const balances = this.calculateSettlement();
                const settlements = this.generateSettlementSuggestions(balances);
                
                document.getElementById('summaryTotal').textContent = Utils.formatCurrency(totalExpense);
                document.getElementById('summaryAvg').textContent = Utils.formatCurrency(avgExpense);
                
                const settlementList = document.getElementById('settlementList');
                if (settlements.length === 0) {
                    settlementList.innerHTML = `
                        <div class="empty-state">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                            </svg>
                            <p>无需结算</p>
                        </div>
                    `;
                } else {
                    settlementList.innerHTML = '';
                    settlements.forEach(settlement => {
                        const item = document.createElement('div');
                        item.className = 'settlement-item';
                        item.innerHTML = `
                            <strong>${settlement.from}</strong> 需要支付给 <strong>${settlement.to}</strong>
                            <div style="font-size: 18px; color: #ff6b6b; margin-top: 5px;">${Utils.formatCurrency(settlement.amount)}</div>
                        `;
                        settlementList.appendChild(item);
                    });
                }
                
                // 显示当前区域
                this.showSection(this.currentSection);
                
                // 更新ARIA标签
                this.updateAriaLabels();
            },

            // 更新ARIA标签
            updateAriaLabels: function() {
                const trip = this.getCurrentTrip();
                if (trip) {
                    document.getElementById('totalExpense').setAttribute('aria-label', `总支出${trip.totalExpense}元`);
                    document.getElementById('memberCount').setAttribute('aria-label', `共${trip.members.length}位成员`);
                }
            },

            // 更新图表
            updateChart: function() {
                const trip = this.getCurrentTrip();
                if (!trip) return;
                
                const chartContainer = document.getElementById('chartContainer');
                
                if (trip.members.length === 0 || trip.expenses.length === 0) {
                    chartContainer.innerHTML = `
                        <div class="empty-state">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
                            </svg>
                            <p>暂无数据</p>
                        </div>
                    `;
                    return;
                }
                
                // 计算每个成员的总支出
                const memberExpenses = {};
                trip.members.forEach(member => {
                    memberExpenses[member] = 0;
                });
                
                trip.expenses.forEach(expense => {
                    memberExpenses[expense.payer] += expense.amount;
                });
                
                // 找出最大值用于缩放
                const maxExpense = Math.max(...Object.values(memberExpenses));
                
                // 创建图表
                chartContainer.innerHTML = '<div class="chart-bars"></div>';
                const barsContainer = chartContainer.querySelector('.chart-bars');
                
                trip.members.forEach(member => {
                    const expense = memberExpenses[member];
                    const height = maxExpense > 0 ? (expense / maxExpense) * 130 : 0;
                    
                    const barWrapper = document.createElement('div');
                    barWrapper.className = 'chart-bar-wrapper';
                    
                    const bar = document.createElement('div');
                    bar.className = 'chart-bar';
                    bar.style.height = height + 'px';
                    bar.textContent = expense > 0 ? Utils.formatCurrency(expense).replace('¥', '¥') : '';
                    
                    const label = document.createElement('div');
                    label.className = 'chart-label';
                    label.textContent = member;
                    
                    barWrapper.appendChild(bar);
                    barWrapper.appendChild(label);
                    barsContainer.appendChild(barWrapper);
                });
            },

            // 导出当前旅行
            exportCurrentTrip: function() {
                const trip = this.getCurrentTrip();
                if (!trip) {
                    this.showToast('没有可导出的旅行数据');
                    return;
                }
                
                const dataStr = JSON.stringify(trip, null, 2);
                const blob = new Blob([dataStr], {type: 'application/json'});
                const url = URL.createObjectURL(blob);
                const link = document.createElement('a');
                link.href = url;
                const date = new Date().toLocaleDateString('zh-CN');
                link.download = `旅行记账_${trip.name}_${date}.json`;
                link.click();
                URL.revokeObjectURL(url);
                this.showToast('当前旅行导出成功');
            },

            // 导出所有旅行
            exportAllTrips: function() {
                if (this.data.trips.length === 0) {
                    this.showToast('没有可导出的数据');
                    return;
                }
                
                const exportData = {
                    exportDate: new Date().toLocaleString('zh-CN'),
                    tripCount: this.data.trips.length,
                    trips: this.data.trips
                };
                
                const dataStr = JSON.stringify(exportData, null, 2);
                const blob = new Blob([dataStr], {type: 'application/json'});
                const url = URL.createObjectURL(blob);
                const link = document.createElement('a');
                link.href = url;
                const date = new Date().toLocaleDateString('zh-CN');
                link.download = `旅行记账_全部_${date}.json`;
                link.click();
                URL.revokeObjectURL(url);
                this.showToast(`全部${this.data.trips.length}个旅行导出成功`);
            },

            // 导入数据
            importData: function(input) {
                const file = input.files[0];
                if (!file) return;
                
                const reader = new FileReader();
                reader.onload = (e) => {
                    Utils.safeOperation(() => {
                        const importedData = JSON.parse(e.target.result);
                        
                        if (importedData.trips && Array.isArray(importedData.trips)) {
                            // 导入所有旅行
                            const newTrips = importedData.trips.filter(trip => 
                                trip.members && Array.isArray(trip.members) && 
                                trip.expenses && Array.isArray(trip.expenses)
                            );
                            
                            // 数据转换：确保份数信息存在
                            newTrips.forEach(trip => {
                                if (trip.expenses) {
                                    trip.expenses.forEach(expense => {
                                        if (expense.participants && expense.participants.length > 0) {
                                            if (typeof expense.participants[0] === 'string') {
                                                // 旧格式转换
                                                expense.participants = expense.participants.map(name => ({
                                                    name: name,
                                                    shares: 1
                                                }));
                                            }
                                        }
                                    });
                                }
                            });
                            
                            if (newTrips.length > 0) {
                                this.data.trips.push(...newTrips);
                                this.showToast(`成功导入${newTrips.length}个旅行`);
                            } else {
                                this.showToast('未找到有效的旅行数据');
                                return;
                            }
                        } else if (importedData.members && importedData.expenses) {
                            // 导入单个旅行（兼容旧格式）
                            const newTrip = {
                                id: Utils.generateId(),
                                name: importedData.name || '导入的旅行',
                                date: importedData.date || new Date().toISOString().split('T')[0],
                                members: importedData.members,
                                expenses: []
                            };
                            
                            // 转换旧格式支出记录的参与者
                            if (importedData.expenses) {
                                newTrip.expenses = importedData.expenses.map(expense => ({
                                    ...expense,
                                    participants: expense.participants.map(p => 
                                        typeof p === 'string' ? {name: p, shares: 1} : p
                                    )
                                }));
                            }
                            
                            this.data.trips.push(newTrip);
                            this.data.currentTripId = newTrip.id;
                            this.showToast('旅行数据导入成功');
                        } else {
                            this.showToast('数据格式错误');
                            return;
                        }
                        
                        this.saveAllData();
                        this.updateTripSelector();
                        this.updateUI();
                        
                    }, '导入失败');
                };
                reader.readAsText(file);
                
                // 清空文件输入
                input.value = '';
            },

            // 清空所有数据
            clearAllData: function() {
                if (!confirm('确定要清空所有数据吗？此操作不可恢复！')) {
                    return;
                }
                
                if (!confirm('再次确认：将删除所有旅行记录、成员和支出数据！')) {
                    return;
                }
                
                localStorage.removeItem(CONFIG.STORAGE_KEY);
                this.data = {
                    currentTripId: null,
                    trips: []
                };
                
                this.updateTripSelector();
                this.updateUI();
                this.showToast('所有数据已清空');
            },

            // 更新旅行信息
            updateTripInfo: function() {
                const trip = this.getCurrentTrip();
                if (!trip) return;
                trip.name = document.getElementById('tripName').value;
                trip.date = document.getElementById('tripDate').value;
                this.saveAllData();
            },

            // 生成报表（支持份数显示）
            printReport: function() {
                const trip = this.getCurrentTrip();
                if (!trip) return;
                
                const totalExpense = trip.expenses.reduce((sum, e) => sum + e.amount, 0);
                const avgExpense = trip.members.length > 0 ? totalExpense / trip.members.length : 0;
                
                const report = {
                    tripName: trip.name,
                    tripDate: trip.date,
                    totalExpense: totalExpense,
                    memberCount: trip.members.length,
                    expenseCount: trip.expenses.length,
                    avgExpense: avgExpense,
                    memberExpenses: {},
                    settlements: this.generateSettlementSuggestions(this.calculateSettlement()),
                    expenses: trip.expenses
                };
                
                // 计算每个成员的总支出
                trip.members.forEach(member => {
                    report.memberExpenses[member] = 0;
                });
                trip.expenses.forEach(expense => {
                    report.memberExpenses[expense.payer] += expense.amount;
                });
                
                const reportWindow = window.open('', '_blank');
                reportWindow.document.write(`
                    <html>
                    <head>
                        <title>旅行记账报表 - ${report.tripName}</title>
                        <style>
                            body { 
                                font-family: 'Microsoft YaHei', Arial, sans-serif; 
                                padding: 20px; 
                                max-width: 800px; 
                                margin: 0 auto;
                                background: linear-gradient(135deg, #f5f7fa 0%, #e4edf5 100%);
                                color: #333;
                            }
                            table { 
                                width: 100%; 
                                border-collapse: collapse; 
                                margin: 20px 0; 
                                background: white;
                                border-radius: 10px;
                                overflow: hidden;
                                box-shadow: 0 4px 10px rgba(0,0,0,0.05);
                            }
                            th, td { 
                                border: 1px solid #e1e8ed; 
                                padding: 12px; 
                                text-align: left; 
                            }
                            th { 
                                background: linear-gradient(135deg, #43cea2 0%, #185a9d 100%);
                                color: white;
                                font-weight: 600;
                            }
                            tr:nth-child(even) { background: #f9f9f9; }
                            .summary { 
                                background: rgba(67, 206, 162, 0.1);
                                padding: 20px; 
                                border-radius: 15px; 
                                margin: 20px 0;
                                border: 1px solid rgba(67, 206, 162, 0.2);
                            }
                            .settlement { 
                                background: rgba(255, 255, 255, 0.7);
                                padding: 15px; 
                                margin: 10px 0; 
                                border-radius: 10px;
                                border-left: 5px solid #43cea2;
                            }
                            h1 { color: #185a9d; text-align: center; margin-bottom: 10px; }
                            h2 { color: #185a9d; border-bottom: 2px solid #43cea2; padding-bottom: 10px; }
                            h3 { color: #185a9d; }
                            .meta { text-align: center; color: #8a9ba8; margin-bottom: 20px; }
                            .total { font-size: 24px; color: #185a9d; font-weight: bold; }
                            .participant-info { font-size: 12px; color: #666; }
                        </style>
                    </head>
                    <body>
                        <h1>🧳 AA旅行记账报表</h1>
                        <h2>${report.tripName}</h2>
                        <div class="meta">出行日期：${report.tripDate} | 参与人数：${report.memberCount} | 支出笔数：${report.expenseCount}</div>
                        
                        <div class="summary">
                            <h3>📊 汇总信息</h3>
                            <p><span class="total">总支出：${Utils.formatCurrency(report.totalExpense)}</span></p>
                            <p>人均费用：${Utils.formatCurrency(report.avgExpense)}</p>
                        </div>
                        
                        <h3>👥 成员支出统计</h3>
                        <table>
                            <tr>
                                <th>成员姓名</th>
                                <th>总支出金额</th>
                                <th>应补/应退</th>
                            </tr>
                            ${Object.entries(report.memberExpenses).map(([member, amount]) => {
                                const balance = report.settlements.filter(s => s.from === member)
                                    .reduce((sum, s) => sum + s.amount, 0) - 
                                    report.settlements.filter(s => s.to === member)
                                    .reduce((sum, s) => sum + s.amount, 0);
                                const balanceText = balance > 0 ? `应补 ${Utils.formatCurrency(balance)}` : 
                                                  balance < 0 ? `应退 ${Utils.formatCurrency(Math.abs(balance))}` : '已结清';
                                const balanceColor = balance > 0 ? '#ff6b6b' : balance < 0 ? '#43cea2' : '#8a9ba8';
                                
                                return `
                                    <tr>
                                        <td>${member}</td>
                                        <td>${Utils.formatCurrency(amount)}</td>
                                        <td style="color: ${balanceColor}; font-weight: 600;">${balanceText}</td>
                                    </tr>
                                `;
                            }).join('')}
                        </table>
                        
                        <h3>💡 结算建议</h3>
                        ${report.settlements.length > 0 ? 
                            report.settlements.map(s => `
                                <div class="settlement">
                                    <strong>${s.from}</strong> 支付给 <strong>${s.to}</strong>：<span style="font-size: 18px; color: #ff6b6b;">${Utils.formatCurrency(s.amount)}</span>
                                </div>
                            `).join('') : 
                            '<div class="settlement">✅ 所有成员费用已结清，无需结算</div>'
                        }
                        
                        <h3>📝 支出明细</h3>
                        <table>
                            <tr>
                                <th>日期时间</th>
                                <th>支出描述</th>
                                <th>金额</th>
                                <th>支出人</th>
                                <th>分摊详情</th>
                            </tr>
                            ${report.expenses.map(expense => `
                                <tr>
                                    <td>${expense.date}</td>
                                    <td>${expense.description}</td>
                                    <td>${Utils.formatCurrency(expense.amount)}</td>
                                    <td>${expense.payer}</td>
                                    <td>
                                        ${expense.participants.map(p => `
                                            <div class="participant-info">${p.name} (${p.shares}份)</div>
                                        `).join('')}
                                    </td>
                                </tr>
                            `).join('')}
                        </table>
                        
                        <p style="text-align: center; margin-top: 30px; color: #8a9ba8;">
                            由 AA旅游记账本 Pro 生成 | 导出时间：${new Date().toLocaleString('zh-CN')}
                        </p>
                    </body>
                    </html>
                `);
                reportWindow.document.close();
                reportWindow.print();
            }
        };

        // 全局错误处理
        window.addEventListener('error', (event) => {
            console.error('全局错误:', event.error);
            TravelApp.showToast('应用发生错误，请刷新页面重试');
        });

        // 初始化应用
        document.addEventListener('DOMContentLoaded', function() {
            TravelApp.init();
        });

        // 定期清理内存
        setInterval(() => {
            // 清理过期的模态框数据
            const modals = ['addExpenseModal', 'editExpenseModal', 'tripManagerModal'];
            modals.forEach(modalId => {
                const modal = document.getElementById(modalId);
                if (modal.style.display === 'none') {
                    // 重置表单以减少内存占用
                    const forms = modal.querySelectorAll('form');
                    forms.forEach(form => form.reset());
                }
            });
        }, 30000);
    </script>
</body>
</html>